package com.lagou.config;

import com.lagou.com.SqlType;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * description XMLMapperBuilder
 * author wy
 * date 2021-04-06 23:51
 **/
public class XMLMapperBuilder
{
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration)
    {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException
    {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        //获取mapper里的标签元素
        List<Element> list = rootElement.elements();

//        List<Element> list = rootElement.selectNodes("//select");
//        list.addAll(rootElement.selectNodes("//insert"));
//        list.addAll(rootElement.selectNodes("//update"));
//        list.addAll(rootElement.selectNodes("//delete"));
        for (Element element : list)
        {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlText);
            switch (element.getQName().getName().toUpperCase())
            {
                case "SELECT":
                    mappedStatement.setSqlType(SqlType.SELECT);
                    break;
                case "INSERT":
                    mappedStatement.setSqlType(SqlType.INSERT);
                    break;
                case "UPDATE":
                    mappedStatement.setSqlType(SqlType.UPDATE);
                    break;
                case "DELETE":
                    mappedStatement.setSqlType(SqlType.DELETE);
                    break;
            }

            configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);
        }

    }
}
